/**
 * Created by Mcgrady on 2016/7/9.
 */
import * as logger from 'winston';
import PlayerModel from '../../database/models/player';
import config from '../../utils/config';

function awardLuckyDraw(prizeIndex, p) {
  if (prizeIndex < 1) return;

  const player = p;
  const prize = config.get('game.prizeIndex2Prize')[prizeIndex - 1];
  const sum = prize.count;
  switch (prize.type) {
    case 'gem':
      PlayerModel.update({_id: player.model._id}, {$inc: {gem: sum}},
        (err) => {
          if (err) {
            logger.error(err);
          } else {
            player.model.coin += sum;
          }
        });
      return;
    case 'gold':
      PlayerModel.update({_id: player.model._id}, {$inc: {gold: sum}},
        (err) => {
          if (err) {
            logger.error(err);
          } else {
            player.model.gold += sum;
          }
        });
      return;
    case 'again':
      PlayerModel.update({_id: player.model._id}, {$inc: {'luckyDraw.time': sum}},
        (err) => {
          if (err) {
            logger.error(err);
          } else {
            player.model.luckyDraw.time += sum;
          }
        });
      return;
    case 'none':
    default:
      return;
  }
}

export function getRandomNum() {
  const randomSeed =  Math.random();
  const probabilityCfg = config.get('game.DrawProbability');
  let total = 0;
  let index = 0;
  for (const key of Object.keys(probabilityCfg)) {
    total += probabilityCfg[key];
    if (total >= randomSeed) {
      index = Number(key) + 1;
      break;
    }
  }

  index = Math.max(index, 1)

  const max = (index * (360 / config.get('game.prizeCount'))) - 5;
  const min = ((index - 1) * (360 / config.get('game.prizeCount'))) + 5;
  return {
    index,
    rotate: Math.floor((Math.random() * ((max - min) + 1)) + min),
  };
}


const resourceHandler = {
  'resource/gem2gold': async(p, message) => {
    const player = p;
    const gem2ExchangeNum = Number(message.gemCount);
    const gem2GoldExchangeRate = config.get('game.gem2GoldExchangeRate');
    let success = false;
    let reason = '';
    let usedGem = 0;
    if (message.gemCount > player.model.gem) {
      reason = '当前所有钻石不足';
    } else {
      const doc = await PlayerModel.update({_id: player.model._id},
        {
          $inc: {
            gem: -gem2ExchangeNum,
            gold: gem2ExchangeNum * gem2GoldExchangeRate,
          },
        });
      if (doc.ok) {
        player.model.coin += gem2ExchangeNum;
        player.model.gold += gem2ExchangeNum * gem2GoldExchangeRate;
        success = true;
        usedGem = gem2ExchangeNum;
      } else {
        reason = '数据存储异常';
      }
    }
    player.sendMessage('gem2goldRet', {
      success,
      usedGem,
      reason,
      getGold: usedGem * gem2GoldExchangeRate,
    });
    return success;
  },

  'resource/luckyDraw': (p, message) => {
    const player = p;
    const luckyDrawNeedGold = config.get('game.luckyDrawNeedGold');
    if (player.model.luckyDraw.time > 0 && player.model.gold >= luckyDrawNeedGold) {
      const timeLeft = player.model.luckyDraw.time - 1;
      const goldLeft = player.model.gold - luckyDrawNeedGold;
      player.model.luckyDraw.time = timeLeft;
      player.model.gold -= luckyDrawNeedGold;
      PlayerModel.update({_id: player.model._id},
        {
          $inc: {
            'luckyDraw.time': -1,
            gold: -1 * luckyDrawNeedGold,
          },
        }, (err) => {
          if (err) logger.error(err)
        });

      const angle2RotateInfo = getRandomNum();
      const finalAngle = (message.rotation + (360 / config.get('game.prizeCount') / 2)) % 360;
      const angle2Rotate = (angle2RotateInfo.rotate - finalAngle) + 1800;
      const prizeIndex = angle2RotateInfo.index;
      awardLuckyDraw(prizeIndex, player);
      player.sendMessage('luckyDrawResult',
        {
          angle2Rotate,
          prizeIndex,
          success: true,
          model: player.model,
        });
    } else {
      const errMsg = player.model.luckyDraw.time === 0 ? '今日抽奖次数已用完' : '金币不足';
      player.sendMessage('luckyDrawResult', {success: false, reason: errMsg});
    }
  },
};
export default resourceHandler;
